import {useStorage} from '@/hooks/useStorage';
import { useToast } from '@/hooks/useToast'

const toast = useToast()

const {getItem} = useStorage();

export type RequestMethod = 'GET' | 'POST';

// const base = 'http://47.111.84.44';
const base = 'https://mini.ronghuahui.com'

const requestFac = (method: RequestMethod) => {
  return function (url: string, data: any = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${base}${url}`,
        data,
        header: {
          ctoken: getItem('SERVER_Token'),
        },
        method,
        success(res: any) {
          if (res.statusCode === 200) {
            const { data } = res
            if (data.code === 200) {
              resolve(data.result);
            } else {
              reject(data.message);
              toast.error(data.message|| '接口请求异常')
            }
          } else {
            reject(res.errMsg);
            toast.error(res.errMsg || '接口请求异常')
          }
        },
        fail(res: any) {
          reject(res.errMsg);
          toast.error(res.errMsg || '接口请求异常')
        },
      });
    });
  };
};

export const get = requestFac('GET');
export const post = requestFac('POST');
